/*
 * Copyright © 2004-2014 chenYuan. All rights reserved.
 * @Website:wwww.jspx.net
 * @Mail:39793751@qq.com
 * @author: chenYuan , 陈原
 * @License: Jspx.net Framework Code is open source (LGPL)，Jspx.net Framework 使用LGPL 开源授权协议发布。
 * @jvm:jdk1.6+  x86/amd64
 *
 */
package com.jspx.txweb.table;

import com.jspx.boot.sign.CongealType;
import com.jspx.boot.sign.MappingType;
import com.jspx.boot.sign.YesNoType;
import com.jspx.json.JSONObject;
import com.jspx.json.NotExpose;
import com.jspx.sober.annotation.*;
import com.jspx.sober.table.OperateTable;
import com.jspx.txweb.IMember;
import com.jspx.txweb.IRole;
import com.jspx.util.StringMap;
import com.jspx.utils.DateUtil;
import com.jspx.utils.NumberUtil;
import com.jspx.utils.StringUtil;
import java.util.*;

/**
 * Created by IntelliJ IDEA.
 * User: chenYuan
 * Date: 2010-7-27
 * Time: 14:50:30
 * 只是基本的用户信息,这些信息为内存中需要经常调用使用的信息
 */
@Table(name = "jspx_member", caption = "默认用户信息", cache = true, cacheName = "memberCache")
public class Member extends OperateTable implements IMember {
    //支持这的登录方式 begin
    @Id(auto = true, type = IDType.serial)
    @Column(caption = "ID", notNull = true)
    private long id;

    //昵称，中文名称方式登录
    @Column(caption = "昵称", length = 50, dataType = "isLengthBetween(2,32)", notNull = true)
    private String name = StringUtil.empty;

    //达人称号
    @Column(caption = "绰号", length = 50, dataType = "isLengthBetween(2,26)", notNull = false)
    private String nickname = StringUtil.empty;

    @NotExpose
    @Column(caption = "拼音", length = 100, hidden = true, notNull = true)
    private String spelling = StringUtil.empty;

    @Column(caption = "邮箱已验证")
    private int mailValidated = YesNoType.NO;

    //允许邮箱登录
    @Column(caption = "邮箱", length = 50, dataType = "isEmail", notNull = false)
    private String mail = StringUtil.empty;


    @Column(caption = "手机已验证")
    private int phoneValidated = YesNoType.NO;

    //手机方式登录
    @Column(caption = "手机", dataType = "isMobile", length = 50)
    private String phone = StringUtil.empty;
    //支持这的登录方式 end

    @Column(caption = "工作电话", length = 20, dataType = "isLengthBetween(0,20)")
    private String workPhone = StringUtil.empty;

    //手机方式登录
    @Column(caption = "卡号", length = 50)
    private String kid = StringUtil.empty;
    //支持这的登录方式 end

    /**
     * 密码保存格式  [md5]904328109384
     *  [Sha]904328109384
     */
    @NotExpose
    @Column(caption = "密码", length = 100, hidden = true, notNull = true)
    private String password = StringUtil.empty;

    //头像
    @Column(caption = "头像URL", length = 240)
    private String faceImage = StringUtil.empty;

    @Column(caption = "性别", option = "男;女;保密", length = 4, notNull = true)
    private String sex = "保密";

    //通过生日计数年龄
    @Column(caption = "生日")
    private Date birthday = DateUtil.empty;

    //积分属性 begin
    @Column(caption = "威望", notNull = true)
    private int prestige = 0;

    //提现活跃度
    @Column(caption = "铜币", notNull = true)
    private int fascination = 0;

    @Column(caption = "信誉值", notNull = true)
    private int credit = 0;
    //积分属性 end

    //用做shop 返点,是虚拟的积分,就用这个作为积分
    @Column(caption = "积分", notNull = true)
    private int integral = 0;

    //奖励
    //数据保存格式  xx奖励=xxx.jpg 一行一个
    @Column(caption = "勋章", length = 250)
    private String medals = StringUtil.empty;

    @Column(caption = "扩展1")
    private int extcredits1 = 0;

    @Column(caption = "扩展2")
    private int extcredits2 = 0;

    //当发生动作的时候，更具配置增加
    @Column(caption = "经验值")
    private int activity = 0;

    //真正的钱
    @Column(caption = "人民币数量")
    private float storeMoney = 0;

    @Column(caption = "折扣组", length = 50)
    private String discountGroup = StringUtil.empty;
    //电子商务end

    //基本属性begin
    @Column(caption = "隐藏信息", option = "0:否1:是;", notNull = true)
    private int hideInfo = 0;

    @Column(caption = "上级ID")
    private long pid = 0;

    @Column(caption = "登陆次数")
    private int loginTimes = 0;

    @Column(caption = "最后登陆时间")
    private Date loginDate = new Date();

    //冻结后不允许登录
    @Column(caption = "冻结", option = "0:激活;1:冻结")
    private int congealType = CongealType.NO_CONGEAL;

    @Column(caption = "被冻结时间", notNull = true)
    private Date congealDate = new Date();

    @Column(caption = "自动冻结日期", notNull = true)
    private Date autoCongealDate = DateUtil.addYear(50);

    //小于当前日期为未禁言
    @Column(caption = "禁言", option = "0:否;1:是")
    private int confineType = YesNoType.NO;

    @Column(caption = "禁言结束日期", notNull = true)
    private Date confineDate = DateUtil.addYear(-1);
    //基本属性end

    @Column(caption = "用户类型", option = "0:个人;1:企业;2:管理人员")
    private int userType = 0;

    @Column(caption = "皮肤", length = 50)
    private String skin = "default";

    @Column(caption = "qq", length = 20)
    private String qq = StringUtil.empty;

    //国家地区
    @Column(caption = "国家", length = 100, defaultValue = "中国")
    private String country = "中国大陆";

    @Column(caption = "省份", length = 50)
    private String province = StringUtil.empty;

    //城市
    @Column(caption = "城市", length = 50)
    private String city = StringUtil.empty;

    @Column(caption = "地址", length = 250)
    private String address = StringUtil.empty;



    @Column(caption = "签名", length = 250)
    private String signature = StringUtil.empty;

    @Column(caption = "备注", length = 250, notNull = true)
    private String remark = StringUtil.empty;

    //作为FTP的基本用户目录，
    @NotExpose
    @Column(caption = "个人目录", length = 250, notNull = true)
    private String uploadFolder = StringUtil.empty;

    /*
     *添加到联系方式
    */
    @Column(caption = "联系人判断", option = "0:所有人;1:禁止所有;2:我关注的会员;3:设置问题", notNull = true)
    private int contactsType = 0;

    @Column(caption = "问题", length = 200)
    private String contactsQuestion = StringUtil.empty;

    @Column(caption = "答案", length = 200)
    private String contactsAnswer = StringUtil.empty;

    @Column(caption = "用户变量", length = 250)
    private String other = StringUtil.empty;

    //电子钥匙登录方式 begin
    @Column(caption = "电子钥匙登录", notNull = true)
    private int useUsb = 0;

    @NotExpose
    @Column(caption = "电子钥匙key", length = 250)
    private String usbKey = StringUtil.empty;
    //电子钥匙登录方式 end

    //用于支付验证等,保存的时候要加密
    @NotExpose
    @Column(caption = "认证密码", length = 50)
    private String payPassword = StringUtil.empty;

    @Column(caption = "使用快速支付积分", length = 50)
    private int useFastPayIntegral = 0;

    @Column(caption = "使用快速支付积分", length = 50)
    private int fastPayIntegral = 10;

    @NotExpose
    @Column(caption = "使用快速支付金额", length = 50)
    private int useFastPayMoney = 0;

    @Column(caption = "快速支付最大金额", length = 50)
    private int fastPayMoney = 10;

    //不保存到数据库  ,这种方式SQL查询太频繁
   // @CalcUnique(caption = "在线", sql = "SELECT count(uid) FROM ${userSessionTable} WHERE uid=?", entity = {UserSession.class}, value = {"id"})
    private boolean online = false;

    //是否已经关注,不保存到数据库,动态计算
    private boolean follow = false;

    //是否已经是联系人,不保存到数据库,动态计算
    private boolean contacts = false;

    @Nexus(mapping = MappingType.OneToMany, name = "id", targetName = "uid", targetEntity = MemberRole.class, chain = true,delete = false)
    private List<MemberRole> memberRoles = new ArrayList<MemberRole>();

    @Nexus(mapping = MappingType.OneToOne, name = "id", targetName = "id", targetEntity = MemberDetails.class, chain = false, delete = true)
    private MemberDetails memberDetails = new MemberDetails();

    public Member() {

    }

    public long getId() {
        return id;
    }

    public void setId(long id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getNickname()
    {
        return nickname;
    }

    public void setNickname(String nickname)
    {
        this.nickname = nickname;
    }

    public String getSpelling() {
        return spelling;
    }

    public void setSpelling(String spelling) {
        this.spelling = spelling;
    }

    public String getKid() {
        return kid;
    }

    public void setKid(String kid) {
        this.kid = kid;
    }

    public String getMail() {
        return mail;
    }

    public void setMail(String mail) {
        this.mail = mail;
    }

    public String getPhone() {
        return phone;
    }

    public void setPhone(String phone) {
        this.phone = phone;
    }

    /**
     * 得到所有密码字符串
     * @return
     */
    public String getPassword() {
        return password;
    }


    /**
     * 密码的hash值
     * @return
     */
    public String getPasswordHash() {
        if (StringUtil.isNULL(password)) return StringUtil.empty;
        if (password.startsWith("[")&&password.contains("]"))
        {
            return StringUtil.substringAfter(password,"]");
        }
        return password;
    }

    /**
     * 密码的秘钥
     * @return
     */
    public String getPasswordHashKey() {
        if (StringUtil.isNULL(password)) return StringUtil.empty;
        if (password.startsWith("[")&&password.contains("]"))
        {
            return StringUtil.substringBetween(password,".","]");
        }
        return StringUtil.empty;
    }


    public boolean equalsPassword(String pw) {
        if (StringUtil.isNULL(password)||StringUtil.isNULL(pw)) return false;
        if (password.startsWith("[")&&password.contains("]"))
        {
            return pw.equalsIgnoreCase(StringUtil.substringAfter(password,"]"));
        }
        return password.equalsIgnoreCase(pw);
    }

    public void setPassword(String password) {
        this.password = password;
    }

    public String getFaceImage() {
        return faceImage;
    }

    public void setFaceImage(String faceImage) {
        this.faceImage = faceImage;
    }

    public String getSex() {
        return sex;
    }

    public void setSex(String sex) {
        this.sex = sex;
    }

    public Date getBirthday() {
        return birthday;
    }

    public void setBirthday(Date birthday) {
        this.birthday = birthday;
    }

    public int getPrestige() {
        return prestige;
    }

    public void setPrestige(int prestige) {
        this.prestige = prestige;
    }

    public int getFascination() {
        return fascination;
    }

    public void setFascination(int fascination) {
        this.fascination = fascination;
    }

    public int getCredit() {
        return credit;
    }

    public void setCredit(int credit) {
        this.credit = credit;
    }

    public String getMedals() {
        return medals;
    }

    public void setMedals(String medals) {
        this.medals = medals;
    }

    public Map<String, String> getMedalMap() {
        Map<String, String> result = new HashMap<String, String>();
        String[] medalArray = StringUtil.split(StringUtil.convertCR(medals), StringUtil.CR);
        for (String value : medalArray) {
            if (StringUtil.isNULL(value) || !value.contains("=")) continue;
            result.put(StringUtil.substringBefore(value, "="), StringUtil.substringAfter(value, "="));
        }
        return result;
    }

    public int getExtcredits1() {
        return extcredits1;
    }

    public void setExtcredits1(int extcredits1) {
        this.extcredits1 = extcredits1;
    }

    public int getExtcredits2() {
        return extcredits2;
    }

    public void setExtcredits2(int extcredits2) {
        this.extcredits2 = extcredits2;
    }

    public float getStoreMoney() {
        return NumberUtil.getRound(storeMoney, 2);
    }

    /*
    public void setStoreMoney(float storeMoney) {
        this.storeMoney = storeMoney;
    }
*/
    public String getDiscountGroup() {
        return discountGroup;
    }

    public void setDiscountGroup(String discountGroup) {
        this.discountGroup = discountGroup;
    }

    public int getHideInfo() {
        return hideInfo;
    }

    public void setHideInfo(int hideInfo) {
        this.hideInfo = hideInfo;
    }

    public long getPid() {
        return pid;
    }

    public void setPid(long pid) {
        this.pid = pid;
    }

    public int getLoginTimes() {
        return loginTimes;
    }

    public void setLoginTimes(int loginTimes) {
        this.loginTimes = loginTimes;
    }

    public Date getLoginDate() {
        return loginDate;
    }

    public void setLoginDate(Date loginDate) {
        this.loginDate = loginDate;
    }

    public int getCongealType() {
        return congealType;
    }

    public void setCongealType(int congealType) {
        this.congealType = congealType;
    }

    public Date getCongealDate() {
        return congealDate;
    }

    public void setCongealDate(Date congealDate) {
        this.congealDate = congealDate;
    }

    public Date getAutoCongealDate() {
        return autoCongealDate;
    }

    public void setAutoCongealDate(Date autoCongealDate) {
        this.autoCongealDate = autoCongealDate;
    }

    public Date getConfineDate() {
        return confineDate;
    }

    public void setConfineDate(Date confineDate) {
        this.confineDate = confineDate;
    }

    public String getSkin() {
        return skin;
    }

    public void setSkin(String skin) {
        this.skin = skin;
    }

    public String getQq() {
        return qq;
    }

    public void setQq(String qq) {
        this.qq = qq;
    }

    public String getCountry() {
        return country;
    }

    public void setCountry(String country) {
        this.country = country;
    }

    public String getProvince() {
        return province;
    }

    public void setProvince(String province) {
        this.province = province;
    }

    public String getCity() {
        return city;
    }

    public void setCity(String city) {
        this.city = city;
    }


    public String getRemark() {
        return remark;
    }

    public void setRemark(String remark) {
        this.remark = remark;
    }

    public String getSignature() {
        return signature;
    }

    public void setSignature(String signature) {
        this.signature = signature;
    }

    public String getUploadFolder() {
        return uploadFolder;
    }

    public void setUploadFolder(String uploadFolder) {
        this.uploadFolder = uploadFolder;
    }

    public int getUseUsb() {
        return useUsb;
    }

    public void setUseUsb(int useUsb) {
        this.useUsb = useUsb;
    }

    public String getUsbKey() {
        return usbKey;
    }

    public void setUsbKey(String usbKey) {
        this.usbKey = usbKey;
    }

    public int getContactsType() {
        return contactsType;
    }

    public void setContactsType(int contactsType) {
        this.contactsType = contactsType;
    }

    public String getContactsQuestion() {
        return contactsQuestion;
    }

    public void setContactsQuestion(String contactsQuestion) {
        this.contactsQuestion = contactsQuestion;
    }

    public String getContactsAnswer() {
        return contactsAnswer;
    }

    public void setContactsAnswer(String contactsAnswer) {
        this.contactsAnswer = contactsAnswer;
    }

    public int getActivity() {
        return activity;
    }

    public void setActivity(int activity) {
        this.activity = activity;
    }

    @Override
    public int getIntegral() {
        return integral;
    }

    /*
    public void setIntegral(int integral) {
        this.integral = integral;
    }
    */

    public Map<String, IRole> getRoles() {
        Map<String, IRole> result = new HashMap<String, IRole>(memberRoles.size());
        for (MemberRole memberRole : memberRoles) {
            Role role = memberRole.getRole();
            if (role == null) continue;
            result.put(role.getNamespace(), role);
        }
        return result;
    }

    public Role getRole(String softName) {
        if (softName == null) return new Role();
        for (MemberRole memberRole : memberRoles) {
            if (softName.equalsIgnoreCase(memberRole.getNamespace())) return memberRole.getRole();
        }
        return new Role();
    }

    public int getMaxUserType()
    {
        if (memberRoles == null || memberRoles.isEmpty()) return 0;
        int result = 0;
        for (MemberRole memberRole : memberRoles) {
            Role role = memberRole.getRole();
            if (role == null) continue;
            if (result < role.getUserType())
                result = role.getUserType();
        }
        return result;
    }


    public String getWorkPhone() {
        return workPhone;
    }

    public void setWorkPhone(String workPhone) {
        this.workPhone = workPhone;
    }

    public boolean isOnline() {
        return online;
    }

    public void setOnline(boolean online) {
        this.online = online;
    }

    public boolean isFollow() {
        return follow;
    }

    public void setFollow(boolean follow) {
        this.follow = follow;
    }

    public boolean isContacts() {
        return contacts;
    }

    public void setContacts(boolean contacts) {
        this.contacts = contacts;
    }

    public List<MemberRole> getMemberRoles() {
        return memberRoles;
    }

    public void setMemberRoles(List<MemberRole> memberRoles)
    {
        if (memberRoles != null)
            this.memberRoles = memberRoles;
    }

    public void setRole(IRole role) {
        if (memberRoles == null) memberRoles = new ArrayList<MemberRole>();
        for (MemberRole memberRole : memberRoles) {
            if (memberRole.getNamespace().equalsIgnoreCase(role.getNamespace())) {
                memberRole.setRole((Role) role);
                memberRole.setUid(id);
                memberRole.setRoleId(role.getId());
                return;
            }
        }
        MemberRole newMemberRole = new MemberRole();
        newMemberRole.setNamespace(role.getNamespace());
        newMemberRole.setUid(id);
        newMemberRole.setRoleId(role.getId());
        newMemberRole.setRole((Role) role);
        memberRoles.add(newMemberRole);
    }

    public String getRoleCaption() {
        StringBuilder sb = new StringBuilder();
        sb.append(":").append("无").append(StringUtil.SEMICOLON);
        if (memberRoles != null)
            for (MemberRole memberRole : memberRoles) {
                IRole role = memberRole.getRole();
                if (role != null)
                    sb.append(role.getNamespace()).append(":").append(role.getName()).append(StringUtil.SEMICOLON);
            }
        if (sb.toString().endsWith(StringUtil.SEMICOLON)) sb.setLength(sb.length() - 1);
        return sb.toString();
    }

    public int getOld() {
        return DateUtil.getYear() - DateUtil.getYear(birthday);
    }

    public String getAddress() {
        return address;
    }

    public void setAddress(String address) {
        this.address = address;
    }

    public int getMailValidated() {
        return mailValidated;
    }

    public void setMailValidated(int mailValidated) {
        this.mailValidated = mailValidated;
    }

    public int getPhoneValidated() {
        return phoneValidated;
    }

    public void setPhoneValidated(int phoneValidated) {
        this.phoneValidated = phoneValidated;
    }

    public MemberDetails getMemberDetails() {
        return memberDetails;
    }

    public void setMemberDetails(MemberDetails memberDetails) {
        this.memberDetails = memberDetails;
    }

    public int getConfineType() {
        return confineType;
    }

    public void setConfineType(int confineType) {
        this.confineType = confineType;
    }

    public int getUseFastPayIntegral() {
        return useFastPayIntegral;
    }

    public void setUseFastPayIntegral(int useFastPayIntegral) {
        this.useFastPayIntegral = useFastPayIntegral;
    }

    public int getFastPayIntegral() {
        return fastPayIntegral;
    }

    public void setFastPayIntegral(int fastPayIntegral) {
        this.fastPayIntegral = fastPayIntegral;
    }

    public int getUseFastPayMoney() {
        return useFastPayMoney;
    }

    public void setUseFastPayMoney(int useFastPayMoney) {
        this.useFastPayMoney = useFastPayMoney;
    }

    public int getFastPayMoney() {
        return fastPayMoney;
    }

    public void setFastPayMoney(int fastPayMoney) {
        this.fastPayMoney = fastPayMoney;
    }

    public String getOther() {
        return other;
    }

    public void setOther(String other) {
        this.other = other;
    }


    public void putValue(String key,String value) {
        StringMap hashMap = new StringMap();
        hashMap.setKeySplit("=");
        hashMap.setLineSplit(StringUtil.CRLF);
        hashMap.setString(other);
        hashMap.put(key, value);
        this.other = hashMap.toString();
    }
    public String getValue(String key) {
        StringMap hashMap = new StringMap();
        hashMap.setKeySplit("=");
        hashMap.setLineSplit(StringUtil.CRLF);
        hashMap.setString(other);
        return hashMap.get(key);
    }

    public String getPayPassword() {
        //如果没有设置，那么就使用登录密码
        if (StringUtil.isNULL(payPassword)) return getPasswordHash();
        return payPassword;
    }

    public void setPayPassword(String payPassword) {
        this.payPassword = payPassword;
    }

    public int getUserType() {
        return userType;
    }

    public void setUserType(int userType) {
        this.userType = userType;
    }


    public void setIntegral(int integral) {
        this.integral = integral;
    }

    public void setStoreMoney(float storeMoney) {
        this.storeMoney = storeMoney;
    }

    public String toString()
    {
        JSONObject json = new JSONObject(this);
        if (memberDetails.getId()<=0)
        {
            json.remove("memberDetails");
        }
        if (memberRoles.isEmpty())
        {
            json.remove("memberRoles");
        }
        return  json.toString(4);
    }

}

